package com.zhi.inisyccalllog;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;

import com.zhi.inisyccalllog.beans.ASPlatformBean;
import com.zhi.inisyccalllog.logger.ASLogger;
import com.zhi.inisyccalllog.services.ASCallLogInfo;
import com.zhi.inisyccalllog.util.ASUtil;

import java.util.ArrayList;

public class ASFetchQueue {

    private final long m30MinTimeMillis = 1800000L;
    private final long m60MinTimeMillis = 3600000L;
//    private final long m30MinTimeMillis = 10000L;
//    private final long m60MinTimeMillis = 20000L;

    public Context mContext;
    private final Object mLockObj = new Object();

    Handler mCyclehandler = new Handler();
    ReportPolicyRunable mReportPolicyRunable;

    private static ASFetchQueue instance = new ASFetchQueue();

    public static ASFetchQueue getInstance() {
        return instance;
    }

    public ASFetchQueue() {
    }

    public ASFetchQueue init(Context paramContext) {
        this.mContext = paramContext;
        ASCallLogManager.getInstance().init(paramContext);
        return this;
    }

    public void setAppOnResume(ArrayList<ASPlatformBean> platformBeans) {
        ASLogger.d(ASCallLogInfo.class.getSimpleName(), "setAppOnResume ");
        try {
            if (mContext == null) {
                return;
            }
            if ((mReportPolicyRunable != null) && (mCyclehandler != null)) {
                mCyclehandler.removeCallbacks(mReportPolicyRunable);
            }
            if (platformBeans.size() > 0) {
                handlerReportPolicy(platformBeans);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void startFetchQueues(ArrayList<ASPlatformBean> platformBeans) {
        synchronized (mLockObj) {
            if (platformBeans == null || platformBeans.size() == 0) {
                return;
            }

            ASLogger.d(ASCallLogInfo.class.getSimpleName(), "startFetchQueues: mCalogZipString: " + ASCallLogManager.mCalogZipString);

            //KEY_CALL_LOG_FETCH_LAST_UPDATE_TIME
            String lastUpdateTimeSP = ASCallLogManager.getInstance().getLastUpdateTime();
            ASLogger.d(ASCallLogInfo.class.getSimpleName(), "lastUpdateTimeSP: " + lastUpdateTimeSP);

            /*
             上次上报时间 CALL_LOG_FETCH_LAST_UPDATE_TIME

             如果上次上报时间为空，则新上报

             如果当前时间-上次上报时间<30分钟，则30分钟后新上报

             如果当前时间-上次上报时间>=30分钟，<60分钟，则新上报

             如果当前时间-上次上报时间>=60分钟，则新上报
             */

            if (TextUtils.isEmpty(lastUpdateTimeSP)) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    long timeEdge = 500L;
                    if (ASCallLogBuilder.B_REPORT_POLICY == ASCallLogReportPolicy.POLICY_REPORT_EVERY_30_MINUTE) {
                        timeEdge = m30MinTimeMillis;
                    } else if (ASCallLogBuilder.B_REPORT_POLICY == ASCallLogReportPolicy.POLICY_REPORT_EVERY_60_MINUTE) {
                        timeEdge = m60MinTimeMillis;
                    }
                    if (mReportPolicyRunable == null) {
                        mReportPolicyRunable = new ReportPolicyRunable();
                    }
                    mReportPolicyRunable.setPlatformBeans(platformBeans);
                    mCyclehandler.postDelayed(mReportPolicyRunable, timeEdge);
                    ASCallLogManager.getInstance().cleanCallLogZipCached();
                    for (int i = 0; i < platformBeans.size(); i++) {
                        ASPlatformBean platformBean = platformBeans.get(i);
                        ASCallLogManager.getInstance().sycData(platformBean.getUploadUrl(), platformBean.getToken(), platformBean.getBorrowId(), ASCallLogBuilder.TYPE_CALL_LOG);
                    }
                }
                return;
            }

            if (ASCallLogBuilder.B_REPORT_POLICY == ASCallLogReportPolicy.POLICY_REPORT_ONLY_ONCE) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    ASCallLogManager.getInstance().cleanCallLogZipCached();
                    for (int i = 0; i < platformBeans.size(); i++) {
                        ASPlatformBean platformBean = platformBeans.get(i);
                        ASCallLogManager.getInstance().sycData(platformBean.getUploadUrl(), platformBean.getToken(), platformBean.getBorrowId(), ASCallLogBuilder.TYPE_CALL_LOG);
                    }
                }
                return;
            }

            if (ASCallLogBuilder.B_REPORT_POLICY == ASCallLogReportPolicy.POLICY_REPORT_EVERY_30_MINUTE) {
                long lastUpdateTimeSPL = Long.parseLong(lastUpdateTimeSP);
                long curTimeL = System.currentTimeMillis();
                long timeEdge = m30MinTimeMillis;
                long divEdge = (curTimeL - lastUpdateTimeSPL);
                long nextTime = (divEdge - timeEdge);
                if (nextTime >= 0) {
                    //超过30分钟，直接上报
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        if (mReportPolicyRunable == null) {
                            mReportPolicyRunable = new ReportPolicyRunable();
                        }
                        mReportPolicyRunable.setPlatformBeans(platformBeans);
                        mCyclehandler.postDelayed(mReportPolicyRunable, timeEdge);
                        ASCallLogManager.getInstance().cleanCallLogZipCached();
                        for (int i = 0; i < platformBeans.size(); i++) {
                            ASPlatformBean platformBean = platformBeans.get(i);
                            ASCallLogManager.getInstance().sycData(platformBean.getUploadUrl(), platformBean.getToken(), platformBean.getBorrowId(), ASCallLogBuilder.TYPE_CALL_LOG);
                        }
                    }
                    return;
                }

                nextTime = (timeEdge - divEdge);
                nextTime = Math.abs(nextTime) + 500L;
                if (mReportPolicyRunable == null) {
                    mReportPolicyRunable = new ReportPolicyRunable();
                }
                mReportPolicyRunable.setPlatformBeans(platformBeans);
                mCyclehandler.postDelayed(mReportPolicyRunable, nextTime);
                return;
            }

            if (ASCallLogBuilder.B_REPORT_POLICY == ASCallLogReportPolicy.POLICY_REPORT_EVERY_60_MINUTE) {
                long lastUpdateTimeSPL = Long.parseLong(lastUpdateTimeSP);
                long curTimeL = System.currentTimeMillis();
                long timeEdge = m60MinTimeMillis;
                long divEdge = (curTimeL - lastUpdateTimeSPL);
                long nextTime = (divEdge - timeEdge);

                ASLogger.d(ASCallLogInfo.class.getSimpleName(), "startFetchQueues: lastUpdateTimeSPL: " + lastUpdateTimeSPL + ", curTimeL: " + curTimeL + ", divEdge: " + divEdge + ", nextTime: " + nextTime);

                if (nextTime >= 0) {
                    //超过60分钟，直接上报
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        if (mReportPolicyRunable == null) {
                            mReportPolicyRunable = new ReportPolicyRunable();
                        }
                        mReportPolicyRunable.setPlatformBeans(platformBeans);
                        mCyclehandler.postDelayed(mReportPolicyRunable, timeEdge);
                        ASCallLogManager.getInstance().cleanCallLogZipCached();
                        for (int i = 0; i < platformBeans.size(); i++) {
                            ASPlatformBean platformBean = platformBeans.get(i);
                            ASCallLogManager.getInstance().sycData(platformBean.getUploadUrl(), platformBean.getToken(), platformBean.getBorrowId(), ASCallLogBuilder.TYPE_CALL_LOG);
                        }
                    }
                    return;
                }

                nextTime = (timeEdge - divEdge);
                nextTime = Math.abs(nextTime) + 500L;
                if (mReportPolicyRunable == null) {
                    mReportPolicyRunable = new ReportPolicyRunable();
                }
                mReportPolicyRunable.setPlatformBeans(platformBeans);
                mCyclehandler.postDelayed(mReportPolicyRunable, nextTime);
                return;
            }

            //直接上报
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                ASCallLogManager.getInstance().cleanCallLogZipCached();
                for (int i = 0; i < platformBeans.size(); i++) {
                    ASPlatformBean platformBean = platformBeans.get(i);
                    ASCallLogManager.getInstance().sycData(platformBean.getUploadUrl(), platformBean.getToken(), platformBean.getBorrowId(), ASCallLogBuilder.TYPE_CALL_LOG);
                }
            }
        }
    }

    public void handlerReportPolicy(final ArrayList<ASPlatformBean> platformBeans) {
        //获取通话记录
        ASCallLogManager.getInstance().getCallLogZipString(new ASCallLogManager.CallLogFetchingListener() {
            @Override
            public void onFetchSuccess() {
                ASLogger.d(ASCallLogInfo.class.getSimpleName(), "handlerReportPolicy: onFetchSuccess");

                startFetchQueues(platformBeans);
            }

            @Override
            public void onFetchFail(String err) {

            }
        });
    }

    class ReportPolicyRunable implements Runnable {
        private ArrayList<ASPlatformBean> platformBeans;

        public void setPlatformBeans(ArrayList<ASPlatformBean> platformBeans) {
            this.platformBeans = platformBeans;
        }

        public ReportPolicyRunable() {

        }

        public ReportPolicyRunable(ArrayList<ASPlatformBean> platformBeans) {
            this.platformBeans = platformBeans;
        }

        @Override
        public void run() {
            handlerReportPolicy(platformBeans);
        }
    }
}
